﻿using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using YAF.Classes.Data;
using YAF.Classes.Utils;

namespace YAF.Controls
{
    /// <summary>
    /// Summary description for Footer.
    /// </summary>
    public class AlphaSort : BaseControl
    {
        public AlphaSort()
        {
            this.Load += new EventHandler(AlphaSort_Load);
        }

        void AlphaSort_Load(object sender, EventArgs e)
        {
            HtmlTable table = new HtmlTable();

            table.Attributes.Add("class", "content");
            table.Width = "100%";

            this.Controls.Add(table);

            // create row
            HtmlTableRow tr = new HtmlTableRow();
            table.Controls.Add(tr);

            // get the localized character set
            string charSet = PageContext.Localization.GetText("LANGUAGE", "CHARSET");
            // get the current selected character (if there is one)
            char selectedLetter = CurrentLetter;

            foreach (char letter in charSet)
            {
                HtmlTableCell cell = new HtmlTableCell();
                cell.Align = "center";

                if (selectedLetter != char.MinValue && selectedLetter == letter)
                {
                    cell.Attributes["class"] = "postheader";
                }
                else
                {
                    cell.Attributes["class"] = "post";
                }

                // create a link to this letter
                HyperLink link = new HyperLink();
                link.Text = letter.ToString();
                link.NavigateUrl = YAF.Classes.Utils.YafBuildLink.GetLinkNotEscaped(YAF.Classes.ForumPages.members, "letter={0}", letter == '#' ? '_' : letter);
                // add it to this td
                cell.Controls.Add(link);

                // add this cell to the row
                tr.Cells.Add(cell);
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        public char CurrentLetter
        {
            get
            {
                char currentLetter = char.MinValue;

                if (HttpContext.Current.Request.QueryString["letter"] != null)
                {
                    try
                    {
                        currentLetter = char.Parse(HttpContext.Current.Request.QueryString["letter"]);
                        if (currentLetter == '_') currentLetter = '#';
                    }
                    catch
                    { 
                    
                    }
                }

                return currentLetter;
            }
        }
    } 
}
